import json
import requests

# 定义 URL
url = 'https://keyue.cloud.baidu.com/online/core/v5/stream/query'
# url1 = 'https://keyue.cloud.baidu.com/core/v5/stream/query'

# 设置请求头
headers = {
    'token': '081fe565-ad01-4eda-acd8-633a79a94ea2',  # 替换为你的实际 token API-key
    'Content-Type': 'application/json',
    # 'uid': 'a75fe0d55cac433caac02302af20cb1c'  # 替换为你的实际用户 ID
}


# 设置请求数据
# data = {
#     "queryText": "我有点肚子疼，请问有什么治疗的方法吗？",
#     "sessionId": "56895c64-e135-46c0-b61b-502bb10fbc7f"
# }

def unit_chat(query_text, session_id):
    data = {
        "queryText": query_text,
        "sessionId": session_id
    }

    # 发送 POST 请求
    response = requests.post(url, headers=headers, json=data)

    # 处理乱码问题：设置响应编码为 'utf-8'
    response.encoding = 'utf-8'

    # 打印返回内容
    # print(response.text)  # 打印返回的文本内容

    # 将返回的结果分割成列表
    split_data = response.text.split("data:")
    # 取出最后一个元素，并去掉首尾的空格
    # 最后一个元素是 JSON 格式的字符串
    dict1 = json.loads(split_data[-1].strip())

    # print("dict1:", dict1)
    response_result = dict1['variables']['last_response']
    session_id = dict1['sessionId']
    return response_result, session_id
    # print("返回结果：" + response_result)


if __name__ == '__main__':
    # 获取session_id
    _, session_id = unit_chat("你好", "")
    while True:
        chat_input = input("请输入：")
        if chat_input == 'Q' or chat_input == 'q' or chat_input == 'bye':
            break
        print(chat_input)
        chat_reply, _ = unit_chat(chat_input, session_id)
        print("用户输入 >>>", chat_input)
        print("Unit回复 >>>", chat_reply)
